from flask import request, jsonify, render_template, current_app, g, session

from info import constants
from info.models import Category
from . import profile_blue
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from info import db
from info.utils.image_storage import storage
from info.models import News


@profile_blue.route('/user_info')
@user_login_data
def user_info():
    """
    返回用户信息数据，由模板渲染
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    data = {
        'user_info': user.to_dict()
    }
    return render_template('news/user.html', data=data)


@profile_blue.route('/base_info', methods=['POST', 'GET'])
@user_login_data
def base_info():
    """
    基本资料的展示与修改
    一、GET请求
    1.获取用户的基信息：签名、昵称、性别
    2. 返回结果，由模板渲染
    二、POST请求
    1. 获取参数nick_name、signature、gender
    2. 检查参数的完整性，并且gender只能是 MAN / WOMAN
    3. 更新mysql数据库的信息，重新设置session
    4. 返回结果
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == 'GET':
        data = {
            'user_info': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    if request.method == 'POST':
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
        print(gender)
        if gender not in ['MAN', 'WOMAN']:
            return jsonify(errno=RET.PARAMERR, errmsg='输入的性别不在范围内')
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        try:
            # db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据提交到mysql数据库失败')
        session['nick_name'] = nick_name

        return jsonify(errno=RET.OK, errmsg='OK')


@profile_blue.route('/pic_info', methods=['POST', 'GET'])
@user_login_data
def pic_info():
    """
    用户头像设置
    1. 获取头像文件数据
    2. 上传到七牛云，返回图片名称，记录到mysql数据库中
    3. 返回前段图片地址时，拼接完整路径
    4. 返回结果
    :return:
    """
    user = g.user
    if request.method == 'GET':
        if user.avatar_url:
            url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
        else:
            url = None
        data = {
            'avatar_url': url
        }
        return render_template('news/user_pic_info.html', data=data)
    image = request.files.get('avatar')
    if not image:
        return jsonify(errno=RET.PARAMERR, errmsg='头像数据读取失败')
    try:
        image_data = image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='图像信息读取失败')

    # 将图像信息上传到七牛云
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='图片上传失败')
    user.avatar_url = image_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据提交到mysql数据库失败')
    data = {
        'avatar_url': constants.QINIU_DOMIN_PREFIX + image_name
    }

    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@profile_blue.route('/news_release', methods=['POST', 'GET'])
@user_login_data
def news_release():
    """
    新闻发布
    一、GET请求
    查询分类信息并返回，由模板渲染数据
    二、POST请求
    1. 获取参数title、category_id、digest、index_image、content
    2. 检查参数的完整性，id的类型转换，图片的上传检验
    3. 提交到mysql数据库
    4. 返回数据
    :return:
    """
    user = g.user
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='新闻分类数据查询错误')
        if not categories:
            return jsonify(errno=RET.DATAERR, errmsg='无新闻分类信息')
        category_list = []
        for category in categories:
            if category.to_dict()['name'] != '最新':
                category_list.append(category.to_dict())
        data = {
            'category_list': category_list
        }
        return render_template('news/user_news_release.html', data=data)
    # POST请求
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')
    print('1', title, '2', category_id, '3', digest, '4', content, '5', index_image)
    if not all([title, category_id, digest, content, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='数据格式不正确')

    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='头像获取失败')

    try:
        index_image_name = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='头像上传失败')

    url = constants.QINIU_DOMIN_PREFIX + index_image_name

    news = News()
    news.category_id = category_id
    news.title = title
    news.digest = digest
    news.index_image_url = url
    news.content = content
    news.user_id = user.id
    news.source = '个人编写'
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据提交到mysql数据库失败')

    return jsonify(errno=RET.OK, errmsg='OK')

